package com.yunhe.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.yunhe.bean.CommodityInfo;
import com.yunhe.test.test;

/**
 * Servlet implementation class ChangeProduct_Servlet
 */
@WebServlet("/ChangeAddDeleteProduct_Servlet")
public class ChangeAddDeleteProduct_Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChangeAddDeleteProduct_Servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		//修改功能
		if("change".equals(request.getParameter("manage"))){
			//此页面不能直接登陆，直接登录会转到商品管理页面
		 	if(request.getParameter("cid")==null){
		 		response.sendRedirect("showProduct_Servlet");
		 	}else{
		 		//设置文件存放路径
				String path="C:\\Users\\Administrator\\git\\testProject\\easyBuy170601\\WebContent\\images\\product\\";
				//设置接受参数
				String productId=request.getParameter("cid");
				String productName="";
				String productDetail="";
				String productPrice="";
				String productNumber="";
				String parentId="";
				String productPath="";
				//设置缓冲区大小
				DiskFileItemFactory fi=new DiskFileItemFactory();
				fi.setSizeThreshold(102400);
				//ServletFileUpload parseRequest（）获取请求表单的所有数据
				ServletFileUpload sfu=new ServletFileUpload(fi);
			    sfu.setHeaderEncoding("UTF-8");
			    try {
					//获取所有表单数据
					List<FileItem> formList=sfu.parseRequest(request);
					System.out.println(formList.toString());
					for(FileItem fileItem:formList){
						// isFormField():判断FileItem对象封装的数据类型(普通表单返回true，文件表单返回false)	
						//如果是普通表单
						if(fileItem.isFormField()){
							//getFileName()获取表单的name属性值 
							//getString()获取普通表单的value getString(String encoding);
							if(fileItem.getFieldName().equals("productName")){
								productName=fileItem.getString("UTF-8");
							}
							if(fileItem.getFieldName().equals("productDetail")){
								productDetail=fileItem.getString("UTF-8");
							}
							if(fileItem.getFieldName().equals("productPrice")){
								productPrice=fileItem.getString("UTF-8");
							}
							if(fileItem.getFieldName().equals("productNumber")){
								productNumber=fileItem.getString("UTF-8");
							}
							if(fileItem.getFieldName().equals("parentId")){
								parentId=fileItem.getString("UTF-8");
							}
						}else{
							//如果是文件表单
							String fileName=fileItem.getName();  //获取文件表单文件名称		
							//上传文件
							productPath="images/product/"+fileName;
							fileItem.write(new File(path+fileName));
					}	
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			  //调用修改方法
		      test te=new test();
		      CommodityInfo commodityinfo=new CommodityInfo();
		      commodityinfo.setCommodityID(Integer.decode(productId));
		      commodityinfo.setCommodityIntroduce(productDetail);
			  commodityinfo.setCommodityName(productName);
			  commodityinfo.setCommodityPrice(Integer.decode(productPrice));
			  commodityinfo.setInventory(Integer.decode(productNumber));
			  commodityinfo.setPictureSource(productPath);
			  commodityinfo.setSmallID(Integer.decode(parentId));
		      te.changec(commodityinfo);
		      response.sendRedirect("showProduct_Servlet");
		 		
		 	}
		}
		//新增功能
		if("add".equals(request.getParameter("manage"))){
			//获取文件上传路径
			String photo=this.getServletContext().getInitParameter("photo");
			System.out.println(photo);
			//获取photos的绝对路径
			String path1=request.getServletContext().getRealPath(photo)+"//";
			System.out.println(path1);	
		
			
			//设置文件存放路径
			String path=path1;
			
			//设置接受参数
			String productName="";
			String productDetail="";
			String productPrice="";
			String productNumber="";
			String parentId="";
			String productPath="";
			//设置缓冲区大小
			DiskFileItemFactory fi=new DiskFileItemFactory();
			fi.setSizeThreshold(102400); 
	        
			//ServletFileUpload parseRequest（）获取请求表单的所有数据
			ServletFileUpload sfu=new ServletFileUpload(fi);
		    sfu.setHeaderEncoding("UTF-8");

			try {
				//获取所有表单数据
				List<FileItem> formList=sfu.parseRequest(request);
				
				for(FileItem fileItem:formList){
					// isFormField():判断FileItem对象封装的数据类型(普通表单返回true，文件表单返回false)
					
					//如果是普通表单
					if(fileItem.isFormField()){
						//getFileName()获取表单的name属性值 
						//getString()获取普通表单的value getString(String encoding);
						if(fileItem.getFieldName().equals("productName")){
							productName=fileItem.getString("UTF-8");
						}
						if(fileItem.getFieldName().equals("productDetail")){
							productDetail=fileItem.getString("UTF-8");
						}
						if(fileItem.getFieldName().equals("productPrice")){
							productPrice=fileItem.getString("UTF-8");
						}
						if(fileItem.getFieldName().equals("productNumber")){
							productNumber=fileItem.getString("UTF-8");
						}
						if(fileItem.getFieldName().equals("parentId")){
							parentId=fileItem.getString("UTF-8");
						}
					}else{
						//如果是文件表单
						String fileName=fileItem.getName();  //获取文件表单文件名称		
						//上传文件
						productPath="images/product/"+fileName;
						fileItem.write(new File(path+fileName));
				}	
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//调用新增方法
			test ts=new test();
			CommodityInfo commodityinfo=new CommodityInfo();
			commodityinfo.setCommodityIntroduce(productDetail);
			commodityinfo.setCommodityName(productName);
			commodityinfo.setCommodityPrice(Integer.decode(productPrice));
			commodityinfo.setInventory(Integer.decode(productNumber));
			commodityinfo.setPictureSource(productPath);
			commodityinfo.setSmallID(Integer.decode(parentId));
			System.out.println(commodityinfo.toString());
			ts.addc(commodityinfo);
			//新增完毕后页面转向回新增页面
			response.sendRedirect("showProduct_Servlet?manage=addproduct");

		}
		//删除功能
		if("delete".equals(request.getParameter("manage"))){
			if(request.getParameter("id")!=null){
				int id=Integer.decode( request.getParameter("id"));
				test te=new test();
			    te.deletec(id);	
			    }
			response.sendRedirect("showProduct_Servlet");
		}
		
		
		
		
		
		
		
		
		
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
